package com.pf.java.File.NIO;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Channel
 *
 * ClassName:NIO2
 * Package:com.pf.java.File.NIO
 *
 * @author: pf
 * @date: 2021/11/9-11:24
 */
public class NIO2 {

    public static void main(String[] args) {
//        copyFile("C:\\Users\\10970\\Desktop\\Java学习笔记\\牛客网学习\\a.txt",
//                "C:\\Users\\10970\\Desktop\\Java学习笔记\\牛客网学习\\a-1.txt");

        appendFile("C:\\Users\\10970\\Desktop\\Java学习笔记\\牛客网学习\\a.txt", "sb");

    }

    public static void copyFile(String srcFilePath, String destFilePath) {
        try (
                FileChannel in = new FileInputStream(srcFilePath).getChannel();
                FileChannel out = new FileOutputStream(destFilePath).getChannel();
                ) {
            // 整体映射
//            ByteBuffer byteBuffer = in.map(FileChannel.MapMode.READ_ONLY, 0, in.size());
//            out.write(byteBuffer);

            // 分批次映射
            ByteBuffer buffer = ByteBuffer.allocate(1024 * 1000);
            while (in.read(buffer) != -1) {
                buffer.flip();
                out.write(buffer);
                buffer.clear();
            }


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //追加内容
    public static void appendFile(String filePath, String content) {
        try (
                FileChannel channel =
                        new RandomAccessFile(filePath, "rw").getChannel();
        ) {
            // 定位至文件末尾
            channel.position(channel.size());
            // 创建Buffer
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 100);
            byteBuffer.flip();
            byteBuffer.put(content.getBytes());
            channel.write(byteBuffer);
            byteBuffer.clear();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
